<template>
  <view>
    <view class="search-box"><uni-search-bar :radius="10089" @input="input" cancelButton="auto" :focus="true"></uni-search-bar></view>
    <uni-list v-if="searchResults.length">
      <uni-list-item ellipsis="1" showArrow :title="item.goods_name" v-for="(item, index) in searchResults" :key="index" @click.native="gotoDetail(item.goods_id)"></uni-list-item>
    </uni-list>
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clean"></uni-icons>
      </view>
      <view class="history-list">
        <view class="tagbox" v-for="(item, index) in historyList1">
          <uni-tag :text="item"  :key="index" @click="gotoGoodsList(item)"></uni-tag>
        </view>
        </view>
    </view>
  </view>
</template>

<script>
export default {
  name: '',
  components: {},
  data() {
    return {
      timer: null,
      kw: '',
      searchResults: [],
      historyList: uni.getStorageSync('kw') || []
    };
  },
  computed: {
    historyList1() {
      return [...this.historyList].reverse();
    }
  },
  created() {},
  mounted() {},
  onLoad() {},
  methods: {
    gotoDetail(id) {
      uni.navigateTo({
        // 指定详情页面的 URL 地址，并传递 goods_id 参数
        url: '/subpkg/goods_detail/goods_detail?goods_id=' + id
      });
    },
    input(e) {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.kw = e;
        this.getSearchResults();
      }, 1000);
    },
    async getSearchResults() {
      if (this.kw.length == 0) {
        this.searchResults = [];
        return;
      }
      this.saveHistory();
      let { data: res } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.kw });
      if (res.meta.status !== 200) return uni.$showMsg();
      this.searchResults = res.message;
    },
    saveHistory() {
      let set = new Set(this.historyList);
      set.delete(this.kw);
      set.add(this.kw);
      this.historyList = Array.from(set);
      uni.setStorageSync('kw', this.historyList);
    },
    clean() {
      this.historyList = [];
      uni.setStorageSync('kw', []);
    },
    gotoGoodsList(item) {
      uni.navigateTo({
        url: '/subpkg/goods_list/goods_list?query=' + item
      });
    }
  }
};
</script>

<style lang="scss">
.uni-searchbar {
  background-color: #c00000;
}
.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;
.tagbox{
margin-right: 10px;
margin-top: 10px;
}
    
  }
}
</style>
